<script setup lang="ts">
import {
  createRoleUserAPI,
  getRoleDetailAPI,
  getTreeListAPI,
  updateRoleAPI,
} from "@/apis/system";
import type { AddRoleParams, RoleData } from "@/types/system";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import type { TreeInstance } from "element-plus/lib/components/index.js";
import { nextTick, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const activeStep = ref(1);
// -------- 步骤一的表单校验 --------
// 表单数据
const roleForm = reactive<AddRoleParams>({
  remark: "",
  roleName: "",
  perms: [],
});

// 表单验证规则
const roleRules = reactive<FormRules<typeof roleForm>>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

// 表单实例，用于统一校验
const roleFormRef = ref<FormInstance>();

// 获取所有权限列表 - 树形结构数据
const treeList = ref<RoleData[]>([]);
const getTreeList = async () => {
  const res = await getTreeListAPI();
  treeList.value = res.data;
};

// 上一步
const prevStep = () => {
  activeStep.value--;
};

// 树形组件
const treeRefs = ref<TreeInstance[]>();
const diabledTreeRefs = ref<TreeInstance[]>();
// 下一步
const nextStep = async () => {
  try {
    // 步骤1：统一表单校验
    if (activeStep.value === 1) {
      await roleFormRef.value?.validate();
    } else if (activeStep.value === 2) {
      // 步骤2: 遍历树形组件，获取所有选中节点的 key 值
      roleForm.perms = []; // 先初始化空数组
      treeRefs.value?.forEach((treeInstance: TreeInstance) => {
        // 获取选中节点的 key 值
        const arrKeys = treeInstance.getCheckedKeys();
        // 追加到分步表单的数组中
        roleForm.perms.push(arrKeys as any);
      });

      // 步骤3: 设置选中权限
      diabledTreeRefs.value?.forEach((treeInstance: TreeInstance, index) => {
        treeInstance.setCheckedKeys(roleForm.perms[index]);
      });

      // 把二维数组变成扁平化，再判断长度
      if (roleForm.perms.flat().length === 0) {
        return ElMessage.error("请角色的选择权限");
      }
    }
    // 步骤增加
    activeStep.value++;
  } catch {}
};

/** 提交表单-新增角色 */
const router = useRouter();
const onSubmit = async () => {
  if (route.query.roleId) {
    // 如果有 id 发送编辑请求
    await updateRoleAPI({
      ...roleForm,
      roleId: Number(route.query.roleId),
    });
  } else {
    // 没有 id 发送新增请求
    await createRoleUserAPI(roleForm);
  }
  ElMessage.success(`保存成功`);
  router.back();
};

// ----- 编辑用户角色 -----
const route = useRoute();
// 页面加载时
onMounted(async () => {
  // 等待 权限列表获取成功后，再设置树形选中
  await getTreeList();
  // 判断是否有 id，如果有 id 就获取角色详情
  if (route.query.roleId) {
    const res = await getRoleDetailAPI(Number(route.query.roleId));
    // 回显表单数据
    roleForm.roleName = res.data.roleName;
    roleForm.remark = res.data.remark;
    roleForm.perms = res.data.perms;
    // 树形组件设置选择状态
    treeRefs.value?.forEach((treeInstance: TreeInstance, index) => {
      treeInstance.setCheckedKeys(res.data.perms[index]);
    });
  }
});
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <!-- 如果路由查询参数 query 中有 id，则显示编辑角色，否则显示添加角色 -->
      <el-page-header
        :content="$route.query.roleId ? '编辑角色' : '添加角色'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="roleFormRef"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
            label-width="100px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input type="textarea" v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="treeRefs"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="{ label: 'title' }"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTreeRefs"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="{ label: 'title', disabled: () => true }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep > 1" @click="prevStep">上一步</el-button>
        <el-button v-if="activeStep < 3" type="primary" @click="nextStep">
          下一步
        </el-button>
        <el-button v-if="activeStep === 3" type="primary" @click="onSubmit">
          {{ $route.query.roleId ? "确认修改" : "确认添加" }}
        </el-button>
      </div>
      {{ roleForm }}
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
